﻿using System;
using System.IO;
using System.Windows.Media;
using OpenLS.Drawing;

namespace OpenLS.Spreadsheet.Formats.Biff.Records.Styling
{
    internal class XFPropColor : XFPropValue
    {
        private byte alpha;
        private byte blue;
        private byte green;
        private byte icv;
        private short nTintShade;
        private byte red;
        private XColorType xclrType;

        public override int Length
        {
            get { return 8; }
        }

        public override void Read(BinaryReader reader, int length)
        {
            Read(reader);
        }

        private void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckClass((t, r) => t.Read(r), (t, w) => t.Write(w), reader, this);
#endif

            byte aType = reader.ReadByte();
            xclrType = (XColorType) (aType >> 1);
            icv = reader.ReadByte();
            nTintShade = reader.ReadInt16();
            red = reader.ReadByte();
            green = reader.ReadByte();
            blue = reader.ReadByte();
            alpha = reader.ReadByte();
        }

        public override void Write(BinaryWriter writer)
        {
            var aType = (byte) ((byte) ((byte) xclrType << 1) | 0x01);
            writer.Write(aType);
            writer.Write(icv);
            writer.Write(nTintShade);
            writer.Write(red);
            writer.Write(green);
            writer.Write(blue);
            writer.Write(alpha);
        }

        public SpreadsheetColor ToColor(BiffReaderWorkbookContext context)
        {
            switch (xclrType)
            {
                case XColorType.XCLRAUTO:
                    return new AutomaticColor(true);
                case XColorType.XCLRINDEXED:
                    return context.GetColor((IcvXF) icv);
                case XColorType.XCLRNINCHED:
                    throw new NotImplementedException();
                case XColorType.XCLRRGB:
                    return new RgbColor(Color.FromArgb(alpha, red, green, blue));
                case XColorType.XCLRTHEMED:
                    return new ThemeColor((ColorSchemeIndex) icv, nTintShade/(double) short.MaxValue);

                default:
                    throw new NotSupportedException();
            }
        }
    }
}